package org.example.controller;

import org.example.pojo.Couplealbum;
import org.example.pojo.Couplename;
import org.example.service.CouplealbumService;
import org.example.service.CouplenameService;
import org.example.service.PhotoService;
import org.example.utils.AilOssUtil;
import org.example.utils.Result;
import org.example.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/coupleAlbum")
public class CouplealbumController {

    @Autowired
    private CouplealbumService couplealbumService;

    @Autowired
    private CouplenameService couplenameService;

    @Autowired
    private PhotoService photoService;

    //相册创建
    @PostMapping("/addCoupleAlbum")
    public Result addCoupleAlbum(String albumName, String url) {

        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");

        Couplename couplename = couplenameService.CoupleFindById(id);

        Integer userId = couplename.getId();

        couplealbumService.addCoupleAlbum(userId, albumName, url);

        return Result.success();
    }

    //相册列表查询
    @GetMapping("/list")
    public Result<List<Couplealbum>> list() {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");

        Couplename couplename = couplenameService.CoupleFindById(id);

        Integer userId = couplename.getId();

        List<Couplealbum> list = couplealbumService.list(userId);

        return Result.success(list);
    }

    //添加相册封面照片
    @PutMapping("/addphoto")
    public Result addphoto(MultipartFile file) throws Exception {
        //把文件上传到本地磁盘
        String originalFilename = file.getOriginalFilename();
        //保证文件名唯一，防止文件覆盖
        String filename = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
        //添加阿里云oss存储
        String url = AilOssUtil.uploadFile(filename, file.getInputStream());

        return Result.success(url);

    }

    //修改相册
    @PutMapping("/editcoupleAlbum")
    public Result editcoupleAlbum(String id, String albumName, String url) {
        couplealbumService.editcoupleAlbum(id,albumName,url);
        return Result.success();
    }

    //相册删除
    @DeleteMapping("/deleteCoupleAlbum")
    public Result deleteCoupleAlbum(String id){
        couplealbumService.deleteCoupleAlbum(id);
        photoService.deleteCoupleAlbumPhoto(id);

        return Result.success();
    }

}
